package compensation

import (
	"bgs/db"
	sqlc "bgs/db/sqlc"
	nsqModel "bgs/nsqp/model"
	activityService "bgs/service/activity"
	"bgs/util"
	"bytes"
	"context"
	"encoding/json"
	"fmt"

	"github.com/nsqio/go-nsq"
	"go.uber.org/zap"
)

var (
	lastCloseEndedActivityMessage *nsqModel.CronMomentMessage = nil
)

// CloseEndedActivityHandler close unpay order message handler
type CloseEndedActivityHandler struct {
	dao             *db.PgDao
	slog            *zap.SugaredLogger
}

// NewCloseEndedActivityHandler create a new handler for CloseEndedActivity
func NewCloseEndedActivityHandler(
	pgdao *db.PgDao,
	slog *zap.SugaredLogger,
) *CloseEndedActivityHandler {
	return &CloseEndedActivityHandler{
		dao:             pgdao,
		slog:            slog.With("module", "CloseEndedActivityHandler"),
	}
}

// HandleMessage implements the Handler interface.
func (h *CloseEndedActivityHandler) HandleMessage(m *nsq.Message) error {
	if len(m.Body) == 0 {
		// Returning nil will automatically send a FIN command to NSQ to mark the message as processed.
		return nil
	}

	h.slog.Infof("CloseEndedActivityMessage=>%s", string(m.Body))

	v := &nsqModel.CronMomentMessage{}
	if decodeErr := json.NewDecoder(bytes.NewReader(m.Body)).Decode(v); decodeErr != nil {
		return fmt.Errorf("无法解析信息[CloseEndedActivityMessage]: %v", decodeErr)
	}
	if lastCloseEndedActivityMessage != nil && lastCloseEndedActivityMessage.TS >= v.TS {
		h.slog.Infof("过时的消息: CloseEndedActivityMessage.TS:%v,v.TS:%v", lastCloseEndedActivityMessage.TS, v.TS)
		return nil
	}

	ctx := context.Background()

	err := h.dao.NewTxRunner().SqlcExecTx(ctx, func(q *sqlc.Queries) (err error) {
		asFeatureTypes := activityService.ActivitiesAsFeature
		limit := util.Int32IfThenElse(v.Data.Limit > 0, v.Data.Limit, 5)
		count, err := q.BatchFinishOrCloseActivitySinceEned(ctx, sqlc.BatchFinishOrCloseActivitySinceEnedParams{
			AsFeatureTypes: asFeatureTypes,
			Limit:          limit,
		})
		h.slog.Infof("a CloseEndedActivityMessage-关闭结束的活动(%d条) ok", count)
		return
	})

	if err != nil {
		return err
	}
	lastCloseEndedActivityMessage = v
	// Returning a non-nil error will automatically send a REQ command to NSQ to re-queue the message.
	return nil
}
